package com.xingchi.tornado.storage.core.utils;

import com.xingchi.tornado.basic.ErrorCode;
import com.xingchi.tornado.core.utils.RequestUtils;
import com.xingchi.tornado.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件工具类
 *
 * @author xingchi
 * @date 2024/12/18 21:40
 */
@Slf4j
public class FileUtils {

    public static void download(String fileName, InputStream is) {
        HttpServletResponse response = RequestUtils.getResponse();
        if (response == null) {
            throw BizException.of(ErrorCode.FILE_DOWNLOAD_FAILED, "无法获取到response对象");
        }
        String fileNameEncode = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileNameEncode);
        response.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE);
        try {
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(is, os);
            response.flushBuffer();
        } catch (Exception e) {
            log.error("文件下载失败：{}", e.getMessage(), e);
            throw BizException.of(ErrorCode.FILE_DOWNLOAD_FAILED);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

}
